package yxk.service.configm;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import yxk.utils.BosUtil;
import yxk.utils.HttpRequestUtil;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 飞书方法服务类
 */
public class FeiShuService {
    private static final Log LOG = LogFactory.getLog(FeiShuService.class);
    private SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 飞书获取人员ID接口、流程创建地址
     */
    private DynamicObject FEISHUPERSON;

    /** 消息发送
     * @param param 飞书请求的参数
     * @return
     */
    public void createWorkflow(JSONObject param ,String toKen){
        DynamicObject feishuperson = getFEISHUPERSON();
        String secreturl = feishuperson.getString("nwg5_secreturl");
        LOG.info("FeiShuService.createWorkflow.param:[{}]",param);
        LOG.info("FeiShuService.createWorkflow.secreturl:[{}]",secreturl);
        try {
            Map header=new HashMap<>();
            header.put("Authorization","Bearer " + toKen);
            String postResult = HttpRequestUtil.getPostResult(secreturl, header, param.toString(), "application/json; charset=utf-8");
            LOG.info("FeiShuService.createWorkflow.postResult:[{}]",postResult);
            JSONObject jsonObject = JSONObject.parseObject(postResult);
            if(jsonObject.getInteger("code") != 0){
                LOG.info("消息发送失败！");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 请求格式封装
     * @param personnel    飞书人员open_id
     * @param name          单据名称
     * @param promoterName  流程发起人名称
     * @param url           流程跳转路径
     * @return
     */
    public JSONObject getBodyMethod(String personnel,String name,String promoterName,String url){
        LOG.info("FeiShuService.bodyMethod.personnels:{},name{},promoterName{},url{}",personnel,name,promoterName,url);
        JSONObject param=new JSONObject();
        List<String> personnels=new ArrayList<>();
        personnels.add(personnel);
        param.put("open_ids",personnels);
        param.put("msg_type","interactive");
        JSONObject card= new JSONObject();
            JSONObject config=new JSONObject();
            config.put("wide_screen_mode",true);
        card.put("config",config);
            List<JSONObject> elements=new ArrayList<>();
                JSONObject elemen0=new JSONObject();
                elemen0.put("tag","div");
                    JSONObject text=new JSONObject();
                        StringBuffer content=new StringBuffer();
                        content.append("**单据名称**\n");
                        content.append(name);
                        content.append("\n\n");
                        content.append("**审批发起人**\n");
                        content.append(promoterName);
                        content.append("\n\n");
                        content.append("**通知时间**\n");
                        content.append(df.format(new Date()));
                    text.put("content",content);
                    text.put("tag","lark_md");
                elemen0.put("text",text);
                JSONObject elemen1=new JSONObject();
                    List<JSONObject> actions=new ArrayList<>();
                        JSONObject action=new JSONObject();
                            JSONObject actionText=new JSONObject();
                                actionText.put("content","点击查看详情");
                                actionText.put("tag","plain_text");
                        action.put("tag","button");
                        action.put("text",actionText);
                        action.put("type","primary");
                        action.put("url",url);//跳转路径
                actions.add(action);
                elemen1.put("actions",actions);
                elemen1.put("tag","action");
            elements.add(elemen0);
            elements.add(elemen1);
        card.put("elements",elements);
            JSONObject header=new JSONObject();
            header.put("template","white");
            JSONObject title=new JSONObject();
            title.put("content","请审批一下流程");
            title.put("tag","plain_text");
            header.put("title",title);
        card.put("header",header);
        param.put("card",card);
        LOG.info("FeiShuService.bodyMethod.param:{}",param);
        return param;
    }

    /**
     * 根据电话号码获取飞书人员ID
     * @param phone 电话号码集合
     * @return
     */
    public Map<String,String> getPersonID(List<String> phone,String toKen){
        LOG.info("FeiShuService.getPersonID.phone:{}",phone);
        Map<String,String> map=new HashMap<>();
        DynamicObject feishuperson = getFEISHUPERSON();
        String url = feishuperson.getString("nwg5_url");
        JSONObject param=new JSONObject();
        param.put("mobiles",phone);
        Map header=new HashMap<>();
        header.put("Authorization","Bearer "+toKen);
        try {
            String postResult = HttpRequestUtil.getPostResult(url, header, param.toString(), "application/json; charset=utf-8");
            LOG.info("RequesUtil.getToKen.postResult:{}",postResult);
            JSONObject datas = JSONObject.parseObject(postResult);
            Integer code = datas.getInteger("code");
            if(code==0) {
                JSONObject data = datas.getJSONObject("data");
                JSONArray userList = data.getJSONArray("user_list");
                for (int i = 0; i < userList.size(); i++) {
                    JSONObject jsonObject = userList.getJSONObject(i);
                    map.put(jsonObject.getString("mobile"), jsonObject.getString("user_id"));
                }
                return map;
            }
            LOG.info("获取人员失败[{}]",code);
            return null;
        }catch (Exception e){
            LOG.error("RequesUtil.getHLYToKen.e{}",e);
            return null;
        }
    }


    /**
     * 获取飞书token
     */
    public String getToKen() {
        DynamicObject feishuperson = getFEISHUPERSON();
        String tokenUrl = feishuperson.getString("nwg5_tokenurl");
        String clientId = feishuperson.getString("nwg5_user");
        String securet = feishuperson.getString("nwg5_password");
        JSONObject json=new JSONObject();
        json.put("app_id",clientId);
        json.put("app_secret",securet);
        try {
            String postResult = HttpRequestUtil.getPostResult(tokenUrl, null, json.toString(), "application/json; charset=utf-8");
            LOG.info("RequesUtil.getToKen.postResult:{}",postResult);
            Map<String, Object> datas = JSONObject.parseObject(postResult);
            String accessToken = (String) datas.get("tenant_access_token");
            return accessToken;
        }catch (Exception e){
            LOG.error("RequesUtil.getHLYToKen.e{}",e);
            return null;
        }
    }

    public static Map<String,String> getUserPhones(List<Long> userIds){
        QFilter qf=new QFilter("id", QCP.in,userIds);
        DynamicObject[] load = BusinessDataServiceHelper.load("bos_user", "number,phone", qf.toArray());
        Map<String,String> map=new HashMap<>();
        for (DynamicObject single : load) {
            String phone = single.getString("phone");
            map.put(phone,single.getString("number"));
        }
        return map;
    }

    public DynamicObject getFEISHUPERSON() {
        if(FEISHUPERSON == null){
            FEISHUPERSON= BosUtil.getConfigUration("FEISHUPERSON");
        }
        return FEISHUPERSON;
    }
}
